package cn.itcast.io.b.bytestream;

import java.io.*;

public class FileInputStreamDemo {

    public static void main(String[] args) throws IOException {

        // 需求1: 读取文件的内容，输出(一次读取一个字节)
        //test1();

        // 需求2：读取文件的内容，输出(一次读取多个字节，循环读)
        //test2();

        // 需求3：读取文件内容，输出(一次读取多个字节，使用缓冲区)
        //test3();
        
        test4();
        
        // 获取文件大小（两种方法）
        //tempTest1();
    }

    private static void test4() throws IOException{
        File file = new File("tempFile\\file.txt");
        InputStream fis = new FileInputStream(file);
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = fis.read(buffer)) != -1){
            System.out.println(new String(buffer,0,len));
        }
    }


    private static void test3() throws IOException {
        File file = new File("tempFile\\file.txt");
        InputStream fis = new FileInputStream(file);
        //byte[] buffer = new byte[(int)file.length()];
        //byte[] buffer = new byte[fis.available()];
        byte[] buffer = new byte[1024];
        int len = fis.read(buffer);
        System.out.println("len:"+len);
        System.out.println(new String(buffer,0,len));
        fis.close();

    }

    private static void test2() throws IOException {
        int ch = 0;
        File file = new File("tempFile\\file.txt");
        InputStream fis = new FileInputStream(file);
        while ((ch = fis.read()) != -1) {
            System.out.print((char) ch);
        }
    }

    private static void test1() throws IOException {

        File file = new File("tempFile\\file.txt");
        InputStream fis = new FileInputStream(file);
        int ch1 = fis.read();
        System.out.println("ch1=" + (char) ch1); // a

        int ch2 = fis.read();
        System.out.println("ch2=" + (char) ch2); // a

        int ch3 = fis.read();
        System.out.println("ch3=" + ch3); // -1

        int ch4 = fis.read();
        System.out.println("ch4=" + ch4); // -1
    }

    private static void tempTest1() throws IOException{
        File file = new File("tempFile\\file.txt");
        System.out.println(file.length());

        FileInputStream fileInputStream = new FileInputStream(file);
        System.out.println(fileInputStream.available());
    }
}
